import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
import routes from './routes'

import 'font-awesome/css/font-awesome.min.css'

import axios from 'axios'
//配置axios的全局基本路径
axios.defaults.baseURL = 'http://127.0.0.1:8080'//'http://81.68.213.26:8080'
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

const router = new VueRouter({
    routes
})

//===============================================登录相关的拦截器
axios.interceptors.request.use(config => {
    //携带token
    let token = localStorage.getItem("token");
    if (token) {
        config.headers['Authorization'] = "Bearer " + token;
    }
    return config;
}, error => {
    Promise.reject(error);
});

// axios 后置拦截器 拦截axios异常，如果是noLogin 定位到登录页
axios.interceptors.response.use(result => {
    let data = result.data;
    if (!data.success && data.message === "noLogin") {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        router.push({path: '/login'});
    }
    return result;
}, error => {
    Promise.reject(error);
});

router.beforeEach((to, from, next) => {
    //alert(to.path)
    //NProgress.start();
    if (to.path == '/login' || to.path == '/shopRegister') {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        next();
    } else {
        let logininfo = JSON.parse(localStorage.getItem("logininfo"));
        if (logininfo) {
            next()
        } else {
            next({path: '/login'})
        }
    }
});
//========================================================登录相关的拦截器

new Vue({
    //el: '#app',
    //template: '<App/>',
    router, store, //components: { App }
    render: h => h(App)
}).$mount('#app')

